<?php

namespace app\admin\model\cms;

use app\common\model\User;
use think\Db;
use think\Model;
use traits\model\SoftDelete;

class Comment extends Model
{
    use SoftDelete;

    // 表名
    protected $name = 'comment';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'type_text',
        'status_text'
    ];

    protected static function init()
    {
        $config = get_addon_config('cms');
        self::afterWrite(function ($row) use ($config) {
            $changedData = $row->getChangedData();
            if (isset($changedData['status']) && isset($config['score']['postcomment'])) {
                if ($changedData['status'] == 'normal') {
                    User::score($config['score']['postcomment'], $row['user_id'], '发表评论');
                } else {
                    User::score(-$config['score']['postcomment'], $row['user_id'], '删除评论');
                }
            }
            self::refreshSourceComments($row['id']);
        });
        self::afterDelete(function ($row) use ($config) {
            $data = Comment::withTrashed()->where('id', $row['id'])->find();
            if ($data) {
                if ($data['status'] == 'normal' && isset($config['score']['postcomment'])) {
                    User::score(-$config['score']['postcomment'], $row['user_id'], '删除评论');
                }
            }
            self::refreshSourceComments($row['id']);
        });
    }

    /**
     * 刷新评论
     * @param int $id 评论ID
     * @return bool
     */
    public static function refreshSourceComments($id)
    {
        $row = self::withTrashed()->where('id', $id)->find();
        if (!$row) {
            return false;
        }
        $model = $row->source;
        if ($model && $model instanceOf \think\Model) {
            $comments = self::where('type', $row['type'])->where('aid', $row['aid'])->where('status', 'normal')->count();
            //评论类型|news:新闻,bbs:论坛,video:视频,plaza:广场,live:直播'
            if (in_array($row['type'],['news','bbs'])){
                $model->save(['comment_count' => $comments]);
            }elseif (in_array($row['type'],['video'])){
                $model->save(['count_comment' => $comments]);
            }
        }
        return true;
    }

    public function getTypeList()
    {
//        return ['archives' => __('Archives'), 'page' => __('Page'), 'special' => __('Special')];
        return ['news' => __('News'), 'bbs' => __('Bbs'),'video' => __('Video'),'plaza' => __('Plaza'),'live' => __('live'),'album' => __('album')];
    }

    public function getStatusList()
    {
        return ['normal' => __('Normal'), 'hidden' => __('Hidden')];
    }

    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['type'];
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : $data['status'];
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    /**
     * 根据类型和ID删除
     */
    public static function deleteByType($type, $aid, $force = false)
    {
        if (!$force) {
            //删除评论
            $commentList = Comment::where(['type' => $type, 'aid' => $aid])->select();
            foreach ($commentList as $index => $item) {
                $item->delete();
            }
        } else {
            //强制删除评论
            $commentList = Comment::withTrashed()->where(['type' => $type, 'aid' => $aid])->select();
            foreach ($commentList as $index => $item) {
                $item->delete(true);
            }
        }
    }

    public function user()
    {
        return $this->belongsTo('\app\common\model\User', 'user_id', '', [], 'LEFT')->field('id,username,nickname,avatar,bio,email')->setEagerlyType(1);
    }

    /**
     * 关联文档模型
     */
    public function archives()
    {
        return $this->belongsTo('News', 'aid', '', [], 'LEFT')->setEagerlyType(0);
    }

    /**
     * 关联单页模型
     */
    public function spage()
    {
        return $this->belongsTo("addons\cms\model\Page", 'aid', '', [], 'LEFT')->setEagerlyType(0);
    }

    /**
     * 关联专题模型
     */
    public function special()
    {
        return $this->belongsTo("addons\cms\model\Special", 'aid', '', [], 'LEFT')->setEagerlyType(0);
    }

    /**
     * 关联模型
     */
    public function source()
    {
        $type = $this->getData('type');
//        $modelArr = ['page' => 'Page', 'archives' => 'Archives', 'special' => 'Special'];
        $modelArr = ['platepost' => 'Platepost', 'news' => 'News'];
        $model = isset($modelArr[$type]) ? $modelArr[$type] : $modelArr['news'];
        return $this->belongsTo($model, "aid");
    }


    // 定义与自身的关联关系
    public function children()
    {
        return $this->hasMany(Comment::class, 'pid','id')->order('id', 'desc');
    }

    /**
     * 点赞总数
     * @param $aid 关联ID
     * @param $type 评论类型|news:新闻,bbs:论坛,video:视频,plaza:广场,live:直播,album:专辑
     * @return int|string
     * @throws \think\Exception
     */
    public static function favTotal($aid, $type){
        return self::where(['aid' => $aid, 'type' =>$type])->count();
    }

    /**
     * 查询全部的子集
     * @param $id 评论id
     * @param array $del_pid_arr
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function deleteCommentAndChildren($id,$del_pid_arr = []){
        $model = Comment::where('pid',$id)->field('id,pid')->select();
        if ($model){
            $del_id_arr[] = $model['id'];
            $this->deleteCommentAndChildren($model['id'],$del_id_arr);
        }else{
            return $del_pid_arr;//
        }

    }
}
